package hnx.ca.util;
import java.io.IOException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.Enumeration;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author TUNGPT.HO
 */
public class TestKeyStore {

    @SuppressWarnings({ "unused", "rawtypes" })
	public static void main(String[] args) throws KeyStoreException, NoSuchProviderException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
        KeyStore keyStore = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
        keyStore.load(null, null);
        if (keyStore == null) {
            System.out.println("Cannot get Keystore");
        }
        Enumeration enumeration = keyStore.aliases();
        while (enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement().toString();
            System.out.println("" + alias);
            keyStore.getCertificateChain(alias);
            java.security.cert.Certificate[] chain = keyStore.getCertificateChain(alias);
            KeyPair keyPair = getPrivateKey(keyStore, alias, "12345".toCharArray());
            if (keyPair != null) {
                System.out.println("PUBLIC KEY: ");
                System.out.println(keyPair.getPublic().toString());
                System.out.println("PRIVATE KEY: ");
                System.out.println(keyPair.getPrivate().toString());
            }            
        }
    }

    public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
        try {
            Key key = keystore.getKey(alias, password);
            if (key instanceof PrivateKey) {
                Certificate cert = keystore.getCertificate(alias);
                PublicKey publicKey = cert.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        } catch (UnrecoverableKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyStoreException e) {
        }
        return null;
    }
}
